package com.roger.uia;

import android.graphics.Rect;
import android.os.Environment;
import android.os.SystemClock;
import android.support.test.uiautomator.UiCollection;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.util.ExcelUtils;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.StrUtils;
import com.roger.uia.helper.UiWatch;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.waitTime;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestBenchmark {
    private static final String TAG = TestBenchmark.class.getSimpleName();
    private final String filePath = Environment.getExternalStorageDirectory() + "/testBenchmark/";

    private String anTuTUPac="com.antutu.ABenchMark";
    private String anTuTUStart="com.antutu.ABenchMark:id/main_test_start_title";
    private String anTuTURestart="com.antutu.ABenchMark:id/main_test_finish_retest";
    private String anTuTUTotalScore="com.antutu.ABenchMark:id/textViewTotalScore";
    private String anTuTuScoreList ="com.antutu.ABenchMark:id/result_details_recyclerView";
    private String anTuTuScore = "com.antutu.ABenchMark:id/textViewScore";

    private String geekBenchPac="com.primatelabs.geekbench";

    private String threeDMarkPac ="com.futuremark.dmandroid.application";
    private String threeDMarkTab="com.futuremark.dmandroid.application:id/flm_tab_layout_benchmarks";
    private String threeDMarkSS="com.futuremark.dmandroid.application:id/flm_fab_benchmark";
    private String threeDMarkSR="com.futuremark.dmandroid.application:id/flm_iv_result_top";
    private String threeDMarkRD="com.futuremark.dmandroid.application:id/flm_rv_score_details_subscores";

    private String androidBenchPac ="com.andromeda.androbench2";
    private String androidBenchTitle ="com.andromeda.androbench2:id/iv_title_message";

    private String GFXPac ="com.glbenchmark.glbenchmark27";
    private String GFXStart = "com.glbenchmark.glbenchmark27:id/main_circleControl";
    private String GFXResult ="com.glbenchmark.glbenchmark27:id/resultdetail_detailList";
    private String GFXResultList ="com.glbenchmark.glbenchmark27:id/results_testList";

    private String pcMarkPac="com.futuremark.pcmark.android.benchmark";
    private String pcMarkPage ="com.futuremark.pcmark.android.benchmark:id/pager";

    @BeforeClass
    public static void beforeClass() throws Throwable {
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
    }

    @Before
    public void setUp()  {
        Log.d(TAG,"-- set up --");
        FileUtils.getPermission();
        UiWatch.getWatcher().runErrorWatcher();
    }

    @After
    public void tearDown() {
        Log.d(TAG,"-- tear down --");
        UiWatch.getWatcher().removeErrorWatcher();
    }

    @AfterClass
    public static void afterClass() throws Throwable {

    }

    @Test
    public void testBenchMark() {
        mDevice.pressHome();
        String wifiName=getJsonString(filePath+"config.json","wifiName");
        String wifiPwd=getJsonString(filePath+"config.json","wifiPwd");
        String googleAccount=getJsonString(filePath+"config.json","googleAccount");
        String googlePwd=getJsonString(filePath+"config.json","googlePwd");
        String testAnTuTu=getJsonString(filePath+"config.json","testAnTuTu");
        String testGeekbench=getJsonString(filePath+"config.json","testGeekbench");
        String test3DMark=getJsonString(filePath+"config.json","test3DMark");
        String testAndrobench=getJsonString(filePath+"config.json","testAndrobench");
        String testGFXBench=getJsonString(filePath+"config.json","testGFXBench");
        String testPCMark=getJsonString(filePath+"config.json","testPCMark");
        int testAnTuTuC=getJsonInt(filePath+"config.json","testAnTuTu","count",0);
        int testGeekbenchC=getJsonInt(filePath+"config.json","testGeekbench","count",0);
        int test3DMarkC=getJsonInt(filePath+"config.json","test3DMark","count",0);
        int testAndrobenchC=getJsonInt(filePath+"config.json","testAndrobench","count",0);
        int testGFXBenchC=getJsonInt(filePath+"config.json","testGFXBench","count",0);
        int testPCMarkC=getJsonInt(filePath+"config.json","testPCMark","count",0);
        int testGap_next_time=getJsonInt(filePath+"config.json","testGap","testGap_next_time",0);
        int testGap_next_app=getJsonInt(filePath+"config.json","testGap","testGap_next_app",0);
        Log.d(TAG,wifiName+wifiPwd+googleAccount+googlePwd);
        Log.d(TAG,testAnTuTu+testGeekbench+test3DMark+testAndrobench+testGFXBench+testPCMark);
        Log.d(TAG,"testGap:"+testGap_next_time+","+testGap_next_app);
        if(testAnTuTu.equals("true")) {
            Log.d(TAG,"testAnTuTu times:" +testAnTuTuC);
            for (int i=0;i<testAnTuTuC;i++){
                test01_AnTuTu_update(i);
                SystemClock.sleep(waitTime * testGap_next_time);
            }
            forceStop(anTuTUPac);
            SystemClock.sleep(waitTime * testGap_next_app);
        }
        if(testGeekbench.equals("true")) {
            Log.d(TAG,"testGeekbench times:" +testGeekbenchC);
            for (int i=0;i<testGeekbenchC;i++){
                test02_GeekBench(i);
                SystemClock.sleep(waitTime * testGap_next_time);
            }
            forceStop(geekBenchPac);
            SystemClock.sleep(waitTime * testGap_next_app);
        }
        if(test3DMark.equals("true")) {
            Log.d(TAG,"test3DMark times:" +test3DMarkC);
            for (int i=0;i<test3DMarkC;i++){
                test03_3DMark(i);
                SystemClock.sleep(waitTime * testGap_next_time);
            }
            forceStop(threeDMarkPac);
            SystemClock.sleep(waitTime * testGap_next_app);
        }
        if(testAndrobench.equals("true")) {
            Log.d(TAG,"testAndrobench times:" +testAndrobenchC);
            for (int i=0;i<testAndrobenchC;i++){
                test04_AndroidBench(i);
                SystemClock.sleep(waitTime * testGap_next_time);
            }
            forceStop(androidBenchPac);
            SystemClock.sleep(waitTime * testGap_next_app);
        }
        if(testGFXBench.equals("true")) {
            Log.d(TAG,"testGFXBench times:" +testGFXBenchC);
            for (int i=0;i<testGFXBenchC;i++){
                test05_GFXBench(i);
                SystemClock.sleep(waitTime * testGap_next_time);
            }
            forceStop(GFXPac);
            SystemClock.sleep(waitTime * testGap_next_app);
        }
        if(testPCMark.equals("true")) {
            Log.d(TAG,"testPCMark times:" +testPCMarkC);
            for (int i=0;i<testPCMarkC;i++){
                test06_PCMark(i);
                SystemClock.sleep(waitTime * testGap_next_time);
            }
            forceStop(pcMarkPac);
        }
    }


    private void test01_AnTuTu(int i) {
        try{
            int open_time_min = getJsonInt(filePath+"config.json","testAnTuTu","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","testAnTuTu","open_time",1);
            int test_time_min = getJsonInt(filePath+"config.json","testAnTuTu","test_time",0);
            int test_time_max = getJsonInt(filePath+"config.json","testAnTuTu","test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(test_time_min)+String.valueOf(test_time_max));
            UiBase.openApp(anTuTUPac);
            SystemClock.sleep(waitTime * open_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[0],"Test",(open_time_max-open_time_min));
            if(UiBase.existObj(UiBase.objSelect[3],anTuTUStart)){
                UiBase.clickObj(UiBase.objSelect[3],anTuTUStart);
            }else {
                UiBase.clickObj(UiBase.objSelect[3],anTuTURestart);
            }
            SystemClock.sleep(waitTime * test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[3],anTuTUTotalScore,(test_time_max-test_time_min));
            getAnTuTuResult(i);
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(anTuTUPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private void test01_AnTuTu_update(int i) {
        try{
            int open_time_min = getJsonInt(filePath+"config.json","testAnTuTu","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","testAnTuTu","open_time",1);
            int test_time_min = getJsonInt(filePath+"config.json","testAnTuTu","test_time",0);
            int test_time_max = getJsonInt(filePath+"config.json","testAnTuTu","test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(test_time_min)+String.valueOf(test_time_max));
            UiBase.openApp(anTuTUPac);
            SystemClock.sleep(waitTime * open_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[0],"Home",(open_time_max-open_time_min));
            if(UiBase.existObj(UiBase.objSelect[3],anTuTUStart)){
                UiBase.clickObj(UiBase.objSelect[3],anTuTUStart);
            }else {
                UiBase.clickObj(UiBase.objSelect[3],anTuTURestart);
            }
            SystemClock.sleep(waitTime * test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[3],anTuTUTotalScore,(test_time_max-test_time_min));
            getAnTuTuResult_update(i);
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(anTuTUPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private void getAnTuTuResult(int i)throws Throwable{
        String[] score = new String[13];
        int timeOut;
        String totalScore = UiBase.getTxtFromObj(UiBase.objSelect[3],anTuTUTotalScore);
        UiScrollable list = new UiScrollable(new UiSelector().resourceId(anTuTuScoreList));
        timeOut = 0;
        while(!UiBase.existObj(UiBase.objSelect[0],"CPU Mathematics Score") && timeOut < 3) {
            timeOut++;
            UiBase.scrollReidClickObj(anTuTuScoreList,UiBase.objSelect[0],"CPU");
        }
        score[0]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"CPU Mathematics Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[1]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"CPU Common Use Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[2]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"CPU Multi-Core Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        timeOut = 0;
        while(!UiBase.existObj(UiBase.objSelect[0],"3D [Marooned] Score") && timeOut < 3) {
            timeOut++;
            UiBase.scrollReidClickObj(anTuTuScoreList,UiBase.objSelect[0],"GPU");
        }
        score[3]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"3D [Marooned] Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[4]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"3D [Coastline] Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[5]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"3D [Refinery] Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        timeOut = 0;
        while(!UiBase.existObj(UiBase.objSelect[0],"Data Security Score") && timeOut < 3) {
            timeOut++;
            UiBase.scrollReidClickObj(anTuTuScoreList,UiBase.objSelect[0],"UX");
        }
        score[6]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"Data Security Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[7]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"Data Processing Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[8]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"Image Processing Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[9]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"User Experience Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        timeOut = 0;
        while(!UiBase.existObj(UiBase.objSelect[0],"RAM Score") && timeOut < 3) {
            timeOut++;
            UiBase.scrollReidClickObj(anTuTuScoreList,UiBase.objSelect[0],"MEM");
        }
        score[10]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"RAM Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[11]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],"ROM Score"),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
        score[12]=totalScore;
        Log.d(TAG,"write results to report now");
        for (int j=0;j<score.length;j++){
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,(6+j),(short) (5+i),score[j]);
        }
        Log.d(TAG,"write results to report finished");
    }

    private void getAnTuTuResult_update(int i)throws Throwable{
        String[] score = new String[16];
        String [] scores={"CPU Mathematical Operations","CPU Common Algorithms","CPU Multi-Core",
                "Terracotta - Vulkan","Coastline - Vulkan","Refinery - OpenGL ES3.1+AEP",
                "RAM Access","ROM APP IO","ROM Sequential Read","ROM Sequential Write","ROM Random Access",
                "Data Security","Data Processing","Image Processing","User Experience"};
        String totalScore = UiBase.getTxtFromObj(UiBase.objSelect[3],anTuTUTotalScore);
        UiScrollable list = new UiScrollable(new UiSelector().resourceId(anTuTuScoreList));
        for (int n=4;n>0;n--){
            list.getChild(new UiSelector().className("android.widget.FrameLayout").index(n)).clickAndWaitForNewWindow();
        }
        for(int p=0;p<15;p++){
            if(!UiBase.existObj(UiBase.objSelect[0],scores[p])) UiBase.scrollReidClickObj(anTuTuScoreList,UiBase.objSelect[0],scores[p]);
            score[p]=getUiObject(list,UiBase.getObj(UiBase.objSelect[0],scores[p]),UiBase.getObj(UiBase.objSelect[3],anTuTuScore)).getText();
            Log.d(TAG,score[p]);
        }
        score[15]=totalScore;
        Log.d(TAG,"write results to report now");
        for (int j=0;j<score.length;j++){
            ExcelUtils.addExcelData(filePath+"antutu_new.xlsx",0,(2+j),(short) (5+i),score[j]);
        }
        Log.d(TAG,"write results to report finished");
    }


    private void test02_GeekBench(int i){
        try{
            int open_time_min = getJsonInt(filePath+"config.json","testGeekbench","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","testGeekbench","open_time",1);
            int cpu_test_time_min = getJsonInt(filePath+"config.json","testGeekbench","cpu_test_time",0);
            int cpu_test_time_max = getJsonInt(filePath+"config.json","testGeekbench","cpu_test_time",1);
            int compute_test_time_min = getJsonInt(filePath+"config.json","testGeekbench","compute_test_time",0);
            int compute_test_time_max = getJsonInt(filePath+"config.json","testGeekbench","compute_test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(cpu_test_time_min)
                    +String.valueOf(cpu_test_time_max)+String.valueOf(compute_test_time_min)+String.valueOf(compute_test_time_max));
            UiBase.openApp(geekBenchPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[0],"CPU",(open_time_max-open_time_min));
            UiBase.waitClickObj(UiBase.objSelect[0],"RUN CPU BENCHMARK",5);
            SystemClock.sleep(waitTime * cpu_test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[0],"RESULT",(cpu_test_time_max-cpu_test_time_min));
            Log.d(TAG,"write results to report now");
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,19,(short) (5+i),getGeekBenchResult(1));
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,20,(short) (5+i),getGeekBenchResult(3));
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressHome();
            UiBase.openApp(geekBenchPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[0],"COMPUTE",(open_time_max-open_time_min));
            UiBase.waitClickObj(UiBase.objSelect[0],"RUN COMPUTE BENCHMARK",5);
            SystemClock.sleep(waitTime * compute_test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[0],"RESULT",(compute_test_time_max-compute_test_time_min));
            Log.d(TAG,"write results to report now");
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,21,(short) (5+i),getGeekBenchResult(1));
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(geekBenchPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private String getGeekBenchResult(int i) throws UiObjectNotFoundException {
        UiObject obj = UiBase.getObj(UiBase.objSelect[0],"Geekbench Score").getChild(new UiSelector().className("android.view.View"))
                .getChild(new UiSelector().className("android.view.View"))
                .getChild(new UiSelector().className("android.view.View").index(i));
        return obj.getText();
    }


    private void test03_3DMark(int i) {
        try{
            int open_time_min = getJsonInt(filePath+"config.json","test3DMark","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","test3DMark","open_time",1);
            int sling_test_time_min = getJsonInt(filePath+"config.json","test3DMark","sling_test_time",0);
            int sling_test_time_max = getJsonInt(filePath+"config.json","test3DMark","sling_test_time",1);
            int ice_test_time_min = getJsonInt(filePath+"config.json","test3DMark","ice_test_time",0);
            int ice_test_time_max = getJsonInt(filePath+"config.json","test3DMark","ice_test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(sling_test_time_min)
                    +String.valueOf(sling_test_time_max)+String.valueOf(ice_test_time_min)+String.valueOf(ice_test_time_max));
            UiBase.openApp(threeDMarkPac);
            SystemClock.sleep(waitTime * open_time_min );
            //test SLING SHOT
            UiBase.waitObjCheck(UiBase.objSelect[0],"My tests",(open_time_max-open_time_min));
            int swipeX =UiBase.getObjX(UiBase.objSelect[3],threeDMarkTab);
            int swipeY =UiBase.getObjY(UiBase.objSelect[3],threeDMarkTab);
            for(int x=0;x<5;x++){
                if(UiBase.existObj(UiBase.objSelect[0],"SLING SHOT")){
                    UiBase.clickObj(UiBase.objSelect[0],"SLING SHOT");
                    break;
                }
                mDevice.swipe(0,swipeY,swipeX,swipeY,100);
            }
            UiBase.waitClickObj(UiBase.objSelect[3],threeDMarkSS,10);
            SystemClock.sleep(waitTime * sling_test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[3],threeDMarkSR,(sling_test_time_max-sling_test_time_min));
            get3DMarkResult(1,i);
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressBack();
            mDevice.pressHome();
            UiBase.openApp(threeDMarkPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitObjCheck(UiBase.objSelect[0],"My tests",(open_time_max-open_time_min));
            //test ICE STORM
            for(int x=0;x<5;x++){
                if(UiBase.existObj(UiBase.objSelect[0],"ICE STORM")){
                    UiBase.clickObj(UiBase.objSelect[0],"ICE STORM");
                    break;
                }
                mDevice.swipe(swipeX,swipeY,0,swipeY,100);
            }
            UiBase.waitClickObj(UiBase.objSelect[3],threeDMarkSS,10);
            SystemClock.sleep(waitTime * ice_test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[3],threeDMarkSR,(ice_test_time_max-ice_test_time_min));
            get3DMarkResult(2,i);
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressBack();
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(threeDMarkPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private void get3DMarkResult(int type,int i) throws UiObjectNotFoundException {
        if(type==1){
            String [] score=new String[8];
            for(int m=0;m<score.length;m++){
                UiObject obj = UiBase.getObj(UiBase.objSelect[3],threeDMarkRD).getChild(new UiSelector().className("android.view.ViewGroup").index(m))
                        .getChild(new UiSelector().className("android.widget.TextView").index(1));
                score[m] =obj.getText().replaceAll(" ","");
            }
            Log.d(TAG,"write results to report now");
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,22,(short) (5+i),score[0]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,23,(short) (5+i),score[1]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,24,(short) (5+i),score[4]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,25,(short) (5+i),score[2]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,26,(short) (5+i),score[3]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,27,(short) (5+i),score[5]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,28,(short) (5+i),score[6]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,29,(short) (5+i),score[7]);
            Log.d(TAG,"write results to report finished");
        }else{
            String [] score=new String[6];
            for(int m=0;m<score.length;m++){
                UiObject obj = UiBase.getObj(UiBase.objSelect[3],threeDMarkRD).getChild(new UiSelector().className("android.view.ViewGroup").index(m))
                        .getChild(new UiSelector().className("android.widget.TextView").index(1));
                score[m] =obj.getText().replaceAll(" ","");
            }
            Log.d(TAG,"write results to report now");
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,30,(short) (5+i),score[0]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,31,(short) (5+i),score[1]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,32,(short) (5+i),score[4]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,33,(short) (5+i),score[2]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,34,(short) (5+i),score[3]);
            ExcelUtils.addExcelData(filePath+"report.xlsx",0,35,(short) (5+i),score[5]);
            Log.d(TAG,"write results to report finished");
        }
    }

    private void test04_AndroidBench(int i){
        try{
            int open_time_min = getJsonInt(filePath+"config.json","testAndrobench","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","testAndrobench","open_time",1);
            int test_time_min = getJsonInt(filePath+"config.json","testAndrobench","test_time",0);
            int test_time_max = getJsonInt(filePath+"config.json","testAndrobench","test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(test_time_min)+String.valueOf(test_time_max));
            UiBase.openApp(androidBenchPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitObjCheck(UiBase.objSelect[3],androidBenchTitle,(open_time_max-open_time_min));
            // 无法点击获取控件，点击坐标
            int startX=getJsonInt(filePath+"xy.json","AndroidBenchStart","x",0);
            int startY=getJsonInt(filePath+"xy.json","AndroidBenchStart","y",0);
            mDevice.click(startX,startY);
            UiBase.waitClickObj(UiBase.objSelect[0],"Yes",5);
            SystemClock.sleep(waitTime * test_time_min);
            UiBase.waitClickObj(UiBase.objSelect[0],"Cancel",(test_time_max-test_time_min));
            SystemClock.sleep(waitTime * 5);
            Log.d(TAG,"write results to report now");
            for(int m=0;m<7;m++){
                mDevice.swipe(0,0,0,0,100);
                ExcelUtils.addExcelData(filePath+"report.xlsx",0,(m+36),(short) (5+i),getAndroidBenchResult(m));
            }
            Log.d(TAG,"write results to report finished");
            //返回measure界面
            int measureX=getJsonInt(filePath+"xy.json","AndroidBenchMeasure","x",0);
            int measureY=getJsonInt(filePath+"xy.json","AndroidBenchMeasure","y",0);
            mDevice.click(measureX,measureY);
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(androidBenchPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private String getAndroidBenchResult(int i) throws UiObjectNotFoundException {
        UiObject obj = UiBase.getObj(UiBase.objSelect[3],"com.andromeda.androbench2:id/TestingView").getChild(new UiSelector().className("android.widget.FrameLayout").index(i))
                .getChild(new UiSelector().className("android.widget.LinearLayout").index(1))
                .getChild(new UiSelector().resourceId("com.andromeda.androbench2:id/row_testing_status"));
        String [] s = obj.getText().split(" ");
        return s[0];
    }


    private void test05_GFXBench(int i) {
        try{
            int open_time_min = getJsonInt(filePath+"config.json","testGFXBench","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","testGFXBench","open_time",1);
            int test_time_min = getJsonInt(filePath+"config.json","testGFXBench","test_time",0);
            int test_time_max = getJsonInt(filePath+"config.json","testGFXBench","test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(test_time_min)+String.valueOf(test_time_max));
            UiBase.openApp(GFXPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[3],GFXStart,(open_time_max-open_time_min));
            SystemClock.sleep(waitTime * test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[3],GFXResultList,test_time_max-test_time_min);
            Log.d(TAG,"write results to report now");
            String [] item ={"Aztec Ruins OpenGL (High Tier)","1440p Aztec Ruins OpenGL (High Tier) Offscreen","Aztec Ruins OpenGL (Normal Tier)",
                    "1080p Aztec Ruins OpenGL (Normal Tier) Offscreen","Aztec Ruins Vulkan (High Tier)","1440p Aztec Ruins Vulkan (High Tier) Offscreen",
                    "Aztec Ruins Vulkan (Normal Tier)","1080p Aztec Ruins Vulkan (Normal Tier) Offscreen","Car Chase","1080p Car Chase Offscreen",
                    "1440p Manhattan 3.1.1 Offscreen","Manhattan 3.1","1080p Manhattan 3.1 Offscreen","Manhattan","1080p Manhattan Offscreen","T-Rex",
                    "1080p T-Rex Offscreen","Tessellation","1080p Tessellation Offscreen","ALU 2","1080p ALU 2 Offscreen","Driver Overhead 2",
                    "1080p Driver Overhead 2 Offscreen","Texturing","1080p Texturing Offscreen","Render Quality","Render Quality (high precision)"};
            for(int m=0;m<27;m++){
                ExcelUtils.addExcelData(filePath+"report.xlsx",0,(43+m),(short) (5+i),getGFXResult(item[m]));
            }
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(GFXPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private String getGFXResult(String testItem) {
        String s="";
        try {
            UiBase.scrollReidClickObj(GFXResultList,UiBase.objSelect[0],testItem);
            SystemClock.sleep(waitTime * 3);
            UiObject obj = mDevice.findObject(new UiSelector().resourceId(GFXResult)).getChild(new UiSelector().className("android.widget.LinearLayout").index(1))
                    .getChild(new UiSelector().className("android.widget.TextView").index(1));
            s=String.format("%.1f",Float.valueOf(obj.getText()));
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
        }catch (Throwable e){
            e.printStackTrace();
        }
        return s;
    }


    private void test06_PCMark(int i) {
        try{
            int open_time_min = getJsonInt(filePath+"config.json","testPCMark","open_time",0);
            int open_time_max = getJsonInt(filePath+"config.json","testPCMark","open_time",1);
            int work2_test_time_min = getJsonInt(filePath+"config.json","testPCMark","work2_test_time",0);
            int work2_test_time_max = getJsonInt(filePath+"config.json","testPCMark","work2_test_time",1);
            int computer_test_time_min = getJsonInt(filePath+"config.json","testPCMark","computer_test_time",0);
            int computer_test_time_max = getJsonInt(filePath+"config.json","testPCMark","computer_test_time",1);
            int storage_test_time_min = getJsonInt(filePath+"config.json","testPCMark","storage_test_time",0);
            int storage_test_time_max = getJsonInt(filePath+"config.json","testPCMark","storage_test_time",1);
            int work_test_time_min = getJsonInt(filePath+"config.json","testPCMark","work_test_time",0);
            int work_test_time_max = getJsonInt(filePath+"config.json","testPCMark","work_test_time",1);
            Log.d(TAG,String.valueOf(open_time_min)+String.valueOf(open_time_max)+String.valueOf(work2_test_time_min)+String.valueOf(work2_test_time_max)
                    +String.valueOf(computer_test_time_min)+String.valueOf(computer_test_time_max)+String.valueOf(storage_test_time_min)+String.valueOf(storage_test_time_max)
                    +String.valueOf(work_test_time_min)+String.valueOf(work_test_time_max));
            UiObject run0 = mDevice.findObject(new UiSelector().text("RUN").index(3));
            UiObject run = mDevice.findObject(new UiSelector().text("RUN").index(4));
            UiScrollable list = new UiScrollable(new UiSelector().text("3DMark Android UI - Score details"));
            //工作2.0效能
            UiBase.openApp(pcMarkPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[3],"android:id/action_bar_spinner",(open_time_max-open_time_min));
            UiBase.waitClickObj(UiBase.objSelect[0],"BENCHMARKS",10);
            UiBase.scrollReidClickObj(pcMarkPage,UiBase.objSelect[1],"Work 2.0 Installed");
            SystemClock.sleep(waitTime * 5);
            if(run.exists()){
                run.clickAndWaitForNewWindow();
            }else{
                run0.clickAndWaitForNewWindow();
            }
            SystemClock.sleep(waitTime * work2_test_time_min);
            UiBase.waitObjCheck(UiBase.objSelect[0],"SCORE DETAILS",(work2_test_time_max-work2_test_time_min));
            list.scrollToEnd(5000);
            Log.d(TAG,"write results to report now");
            UiObject resultList = mDevice.findObject(new UiSelector().className("android.widget.ListView").index(6));
            for(int m=0;m<6;m++){
                if(resultList.exists()){
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(70+m),(short) (5+i),getPcMarkResult(6,((m+1)*2)));
                }else{
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(70+m),(short) (5+i),getPcMarkResult(4,(2*m+1)));
                }
            }
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressBack();
            mDevice.pressHome();
            //计算机视觉
            UiBase.openApp(pcMarkPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[3],"android:id/action_bar_spinner",(open_time_max-open_time_min));
            UiBase.waitClickObj(UiBase.objSelect[0],"BENCHMARKS",10);
            UiBase.scrollReidClickObj(pcMarkPage,UiBase.objSelect[1],"Computer Vision Installed");
            SystemClock.sleep(waitTime * 5);
            if(run.exists()){
                run.clickAndWaitForNewWindow();
            }else{
                run0.clickAndWaitForNewWindow();
            }
            SystemClock.sleep(waitTime * computer_test_time_min);
            UiBase.waitObj(UiBase.objSelect[0],"SCORE DETAILS",(computer_test_time_max-computer_test_time_min));
            list.scrollToEnd(5000);
            Log.d(TAG,"write results to report now");
            for(int m=0;m<4;m++){
                if(resultList.exists()){
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(76+m),(short) (5+i),getPcMarkResult(6,((m+1)*2)));
                }else{
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(76+m),(short) (5+i),getPcMarkResult(4,(2*m+1)));
                }
            }
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressBack();
            mDevice.pressHome();
            //存储
            UiBase.openApp(pcMarkPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[3],"android:id/action_bar_spinner",(open_time_max-open_time_min));
            UiBase.waitClickObj(UiBase.objSelect[0],"BENCHMARKS",10);
            UiBase.scrollReidClickObj(pcMarkPage,UiBase.objSelect[1],"Storage Installed");
            SystemClock.sleep(waitTime * 5);
            if(run.exists()){
                run.clickAndWaitForNewWindow();
            }else{
                run0.clickAndWaitForNewWindow();
            }
            SystemClock.sleep(waitTime * storage_test_time_min);
            UiBase.waitObj(UiBase.objSelect[0],"SCORE DETAILS",(storage_test_time_max-storage_test_time_min));
            list.scrollToEnd(5000);
            Log.d(TAG,"write results to report now");
            for(int m=0;m<13;m++){
                if(resultList.exists()){
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(80+m),(short) (5+i),getPcMarkResult(6,((m+1)*2)));
                }else {
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(80+m),(short) (5+i),getPcMarkResult(4,(2*m+1)));
                }
            }
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressBack();
            mDevice.pressHome();
            //工作效能
            UiBase.openApp(pcMarkPac);
            SystemClock.sleep(waitTime * open_time_min );
            UiBase.waitClickObj(UiBase.objSelect[3],"android:id/action_bar_spinner",(open_time_max-open_time_min));
            UiBase.waitClickObj(UiBase.objSelect[0],"BENCHMARKS",10);
            UiBase.scrollReidClickObj(pcMarkPage,UiBase.objSelect[1],"Work Installed");
            SystemClock.sleep(waitTime * 5);
            if(run.exists()){
                run.clickAndWaitForNewWindow();
            }else{
                run0.clickAndWaitForNewWindow();
            }
            SystemClock.sleep(waitTime * work_test_time_min);
            UiBase.waitObj(UiBase.objSelect[0],"SCORE DETAILS",(work_test_time_max-work_test_time_min));
            list.scrollToEnd(5000);
            Log.d(TAG,"write results to report now");
            for(int m=0;m<5;m++){
                if(resultList.exists()){
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(93+m),(short) (5+i),getPcMarkResult(6,((m+1)*2)));
                }else{
                    ExcelUtils.addExcelData(filePath+"report.xlsx",0,(93+m),(short) (5+i),getPcMarkResult(4,(2*m+1)));
                }
            }
            Log.d(TAG,"write results to report finished");
            mDevice.pressBack();
            SystemClock.sleep(waitTime * 3);
            mDevice.pressBack();
            mDevice.pressHome();
        }catch (Throwable e){
            forceStop(pcMarkPac);
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private String getPcMarkResult(int listI,int viewI) throws UiObjectNotFoundException {
        UiObject result = mDevice.findObject(new UiSelector().className("android.widget.ListView").index(listI)).getChild(new UiSelector().className("android.view.View").index(viewI));
        String [] s = result.getText().split(" ");
        return s[0];
    }



    public void allowPermission() throws UiObjectNotFoundException {
        UiBase.waitObj(UiBase.objSelect[3],StrUtils.allowBtn,5);
        while (UiBase.existObj(UiBase.objSelect[3],StrUtils.allowBtn)){
            UiBase.clickObj(UiBase.objSelect[3],StrUtils.allowBtn);
            SystemClock.sleep(waitTime);
        }
    }

    public void clearAllApps(){
        try{
            mDevice.pressRecentApps();
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.snapshot,waitTime);
            if(UiBase.existObj(UiBase.objSelect[3],StrUtils.snapshot)){
                while(!UiBase.existObj(UiBase.objSelect[2],StrUtils.clearAll)){
                    mDevice.swipe(20, StrUtils.SCREEN_H/2, StrUtils.SCREEN_W  - 20, StrUtils.SCREEN_H/2, 10);
                }
                UiBase.clickObj(UiBase.objSelect[2],StrUtils.clearAll);
            }
        }catch (Throwable e){
            Log.d(TAG,"clear all apps fail!");
        }finally {
            mDevice.pressHome();
        }
    }


    // 解析json数据
    private String getJsonString(String Path, String thisId){
        String string=null;
        try {
            File file = new File(Path);
            FileInputStream isr = new FileInputStream(file);
            BufferedReader bf = new BufferedReader(new InputStreamReader(isr));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            JSONObject root = new JSONObject(stringBuilder.toString());
            JSONArray array = root.getJSONArray("config");
            for (int i = 0; i < array.length(); i++) {
                JSONObject data = array.getJSONObject(i);
                String id = data.getString("id");
                if (thisId.equals(id)) {
                    string = (data.getString("value"));
                }
            }
            bf.close();
            isr.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return string;
    }

    private int getJsonInt(String Path, String thisId, String desc, int x){
        String counts="";
        try {
            File file = new File(Path);
            FileInputStream isr = new FileInputStream(file);
            BufferedReader bf = new BufferedReader(new InputStreamReader(isr));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            JSONObject root = new JSONObject(stringBuilder.toString());
            JSONArray array = root.getJSONArray("config");
            for (int i = 0; i < array.length(); i++) {
                JSONObject data = array.getJSONObject(i);
                String id = data.getString("id");
                if (thisId.equals(id)) {
                    counts = data.getString(desc);
                }
            }
            bf.close();
            isr.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        String [] count=counts.split("-");
        return Integer.valueOf(count[x]);
    }

    // 判断两个控件是否在同一行
    private static boolean isSameLine(UiObject obj1, UiObject obj2) throws UiObjectNotFoundException {
        Rect first = obj1.getBounds();
        Rect second = obj2.getBounds();
        if(Math.pow(first.width(),2)== Math.pow(StrUtils.SCREEN_W,2)
                || Math.pow(second.width(),2)== Math.pow(StrUtils.SCREEN_W,2) ){
            throw new RuntimeException("args is error, width == screen width");
        }
        return first.top< second.bottom && first.bottom > second.top ; // 比较区域
    }

    // 返回同行的控件
    private static UiObject getUiObject(UiCollection uic, UiObject uio, UiObject uio2) throws UiObjectNotFoundException {
        UiObject obj = null;
        UiSelector uis = uio2.getSelector();
        for(int i=0; i< uic.getChildCount(uis); i++){
            UiObject uiObject = uic.getChildByInstance(uis, i);
            boolean result = isSameLine(uio, uiObject);
            if(result){
                obj = uiObject;
                break;
            }
        }
        if(obj == null){ throw new RuntimeException("Get "+ uio.getSelector()+" same line UiObject error");}
        return obj;
    }

    private void forceStop(String pacName){
        try {
            mDevice.executeShellCommand("am force-stop "+pacName);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    @Test
    public void test()throws Throwable{
        Log.d(TAG,"debug");
//        ExcelUtils.addExcelData(filePath+"antutu_new.xlsx",0,8,(short) 6,"test111");
//        ExcelUtils.addExcelData(filePath+"report.xlsx",0,8,(short) 6,"test");
        getAnTuTuResult_update(0);
    }

}
